﻿using FastBuild.TimeJob;
using SqlSugar;
using System.Text.RegularExpressions;
using Wechat_PublicNumber.Common;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.Repository;

namespace Wechat_PublicNumber.Jobs
{
    [SkipWhileExecuting]
    public class WorkOvertimeMailJob : DataAccess, IJob
    {

        #region DI

        [Autowired]
        private WxTemplateRepository _templateRepository;

        [Autowired]
        private WxHttpInvoke _wxHttpInvoke;

        [Autowired]
        private MailFactory mailFactory;

        [Autowired]
        private WorkRepository _workRepository;

        #endregion

        public async Task Execute()
        {
            try
            {
                _logger.Info("WorkOvertimeMailJob Begin", "WorkOvertimeMailJob");

                MailClient _mailClient = mailFactory.CreateMailClient();

                var nowTime = DateTime.Now;

                var unReadMail = _mailClient.GetEmailByFolder();

                foreach (var item in unReadMail)
                {
                    var oneMail = _mailClient.GetEmailByUniqueId(item.UniqueId);

                    var userInfo = await WXDb.Queryable<Entity.UserInfo>().Where(s => s.Email == oneMail.Address).FirstAsync();

                    string message = "加班记录已更新，";
                    _logger.Info($"{oneMail.Subject} 开始处理", "WorkOvertimeMailJob");

                    if (userInfo is not null && oneMail.Subject.Contains("加班") && !string.IsNullOrEmpty(oneMail.BodyText))
                    {
                        //开始处理
                        var jbData = MatchJbList(oneMail.BodyText);

                        _logger.Info($"{oneMail.Subject} 数据处理完成\nBody:\n{oneMail.BodyText}\nData：{Newtonsoft.Json.JsonConvert.SerializeObject(jbData)}", "WorkOvertimeMailJob");

                        if (jbData is not null && jbData.Count > 0)
                        {
                            List<Work> workList = new List<Work>();
                            jbData = jbData.Where(s => s.Date >= DateTime.Parse($"{nowTime.Year}-01-01")).ToList();

                            foreach (var jb in jbData)
                            {
                                workList.Add(new Work()
                                {
                                    Hours = jb.Hour,
                                    OpenID = userInfo.OpenID,
                                    WhichDay = jb.Date,
                                    Type = WorkTypeEmnu.WorkOvertime,
                                    CreateTime = nowTime
                                });
                                message += $"{jb.Date:yyyy-MM-dd}({jb.Hour}h)，";
                            }

                            //入库 并且 发送消息提醒
                            if (workList.Count > 0)
                            {
                                await WXDb.Insertable(workList).ExecuteCommandAsync();

                                var residueTime = await _workRepository.GetResidueWorkTime(userInfo.OpenID);

                                message += $"剩余调休时长{residueTime}h。";

                                var pushData = await _templateRepository.GetTemplateData(WeChatTemplateEnum.CommonMessage, userInfo.OpenID, new { Message = message });
                                if (pushData is not null) await _wxHttpInvoke.PushTemplate(pushData);

                                _logger.Info($"{oneMail.Subject} 入库成功，Data：{Newtonsoft.Json.JsonConvert.SerializeObject(workList)}", "WorkOvertimeMailJob");
                            }
                        }
                    }

                    //设置已读
                    _mailClient.SetMailFlag(item.UniqueId, MailKit.MessageFlags.Seen);
                    _logger.Info($"{oneMail.Subject} 设置已读成功", "WorkOvertimeMailJob");
                }
                _logger.Info($"WorkOvertimeMailJob End", "WorkOvertimeMailJob");

                GC.Collect();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "WorkOvertimeMailJob Error", "WorkOvertimeMailJob");
            }
        }

        List<JbClass> MatchJbList(string text)
        {
            List<JbClass> jbClass = new List<JbClass>();

            text = text.Replace("：", ":");

            var startIndex = text.IndexOf("时间:", 0);
            while (startIndex != -1)
            {
                if (startIndex == text.Length) break;

                var endIndex = text.IndexOf("时间:", startIndex + 1);
                if (endIndex == -1)
                    endIndex = text.Length;

                var tempText = text.Substring(startIndex, endIndex - startIndex);
                // 提取时间
                string timePattern = @"时间:(\d{4}-\d{1,2}-\d{1,2})";
                var time = ExtractValue(tempText, timePattern);

                // 提取小时
                string hoursPattern = @"小时:(\d+(\.\d)?)小时";
                var hour = ExtractValue(tempText, hoursPattern);

                jbClass.Add(new JbClass()
                {
                    Date = DateTime.Parse(time),
                    Hour = decimal.Parse(hour)
                });

                startIndex = endIndex;
            }

            return jbClass;
        }

        string ExtractValue(string input, string pattern)
        {
            Match match = Regex.Match(input, pattern);
            if (match.Success)
            {
                return match.Groups[1].Value;
            }
            else
            {
                return "未找到匹配项";
            }
        }

        public class JbClass
        {
            public DateTime Date { get; set; }

            public decimal Hour { get; set; }
        }
    }
}
